import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../controllers/buy_record_controller.dart';
import '../controllers/position_controller.dart';



class EditBuyRecordPage extends StatefulWidget {
  final int recordId;

  const EditBuyRecordPage({Key? key, required this.recordId}) : super(key: key);

  @override
  _EditBuyRecordPageState createState() => _EditBuyRecordPageState();
}

class _EditBuyRecordPageState extends State<EditBuyRecordPage> {
  final BuyRecordController _controller = Get.find();
  final _formKey = GlobalKey<FormState>();

  final _symbolController = TextEditingController();
  final _nameController = TextEditingController();
  final _priceController = TextEditingController();
  final _quantityController = TextEditingController();

  DateTime _selectedDate = DateTime.now();
  bool _isLoading = true;
  bool _isLoadingName = false;

  @override
  void initState() {
    super.initState();
    _loadRecordData();
    _symbolController.addListener(_onSymbolChanged);
  }

  @override
  void dispose() {
    _symbolController.removeListener(_onSymbolChanged);
    _symbolController.dispose();
    _nameController.dispose();
    _priceController.dispose();
    _quantityController.dispose();
    super.dispose();
  }

  void _loadRecordData() async {
    try {
      final record = await _controller.getBuyRecordById(widget.recordId);

      if (record != null && mounted) {
        setState(() {
          _symbolController.text = record.symbol;
          _nameController.text = record.name;
          _priceController.text = record.buyPrice.toString();
          _quantityController.text = record.quantity.toString();
          _selectedDate = record.buyDate;
          _isLoading = false;
        });
      }
    } catch (e) {
      Get.snackbar(
        '错误',
        '加载记录失败: $e',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.red[100],
        colorText: Colors.red[900],
        duration: const Duration(seconds: 4),
      );
      Get.back();
    }
  }

  void _onSymbolChanged() async {
    final symbol = _symbolController.text.trim();
    if (_isValidStockSymbol(symbol)) {
      setState(() {
        _isLoadingName = true;
      });

      final name = await _controller.getStockName(symbol);

      if (mounted) {
        setState(() {
          _isLoadingName = false;
          if (name != null) {
            _nameController.text = name;
          } else {
            _nameController.clear();
          }
        });
      }
    } else {
      setState(() {
        _nameController.clear();
      });
    }
  }

  bool _isValidStockSymbol(String symbol) {
    final regex = RegExp(r'^(sh|sz)\d{6}$');
    return regex.hasMatch(symbol);
  }

  Future<void> _selectDate(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: _selectedDate,
      firstDate: DateTime(2000),
      lastDate: DateTime.now(),
    );

    if (picked != null && picked != _selectedDate) {
      setState(() {
        _selectedDate = picked;
      });
    }
  }

  Future<void> _submitForm() async {
    if (_formKey.currentState!.validate()) {
      try {
        final success = await _controller.updateBuyRecord(
          id: widget.recordId,
          symbol: _symbolController.text.trim(),
          name: _nameController.text.trim(),
          buyPrice: double.parse(_priceController.text),
          quantity: int.parse(_quantityController.text),
          buyDate: _selectedDate,
        );

        if (success) {
          // 显示成功提示
          Get.snackbar(
            '成功',
            '买入记录已更新',
            snackPosition: SnackPosition.BOTTOM,
            backgroundColor: Colors.green[100],
            colorText: Colors.green[900],
            duration: const Duration(seconds: 2),
          );

          // 刷新持仓数据
          if (Get.isRegistered<PositionController>()) {
            await Get.find<PositionController>().refreshData();
          }

          // 关闭当前页面
          Navigator.of(context).pop(true);
        } else {
          // 显示失败提示
          Get.snackbar(
            '错误',
            '更新买入记录失败',
            snackPosition: SnackPosition.BOTTOM,
            backgroundColor: Colors.red[100],
            colorText: Colors.red[900],
            duration: const Duration(seconds: 4),
          );
        }
      } catch (e) {
        // 显示异常提示
        Get.snackbar(
          '错误',
          '更新买入记录时发生异常: $e',
          snackPosition: SnackPosition.BOTTOM,
          backgroundColor: Colors.red[100],
          colorText: Colors.red[900],
          duration: const Duration(seconds: 4),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return Scaffold(
        appBar: AppBar(
          title: const Text('编辑买入记录'),
          backgroundColor: Colors.blue[700],
          foregroundColor: Colors.white,
        ),
        body: const Center(child: CircularProgressIndicator()),
      );
    }

    return Scaffold(
      appBar: AppBar(
        title: const Text('编辑买入记录'),
        backgroundColor: Colors.blue[700],
        foregroundColor: Colors.white,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Navigator.of(context).pop(false),
        ),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              TextFormField(
                controller: _symbolController,
                decoration: const InputDecoration(
                  labelText: '股票代码*',
                  hintText: '例如: sh601006 或 sz000001',
                  border: OutlineInputBorder(),
                  prefixIcon: Icon(Icons.tag),
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入股票代码';
                  }
                  if (!_isValidStockSymbol(value)) {
                    return '股票代码格式应为shXXXXXX或szXXXXXX';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: _nameController,
                decoration: InputDecoration(
                  labelText: '股票名称*',
                  border: const OutlineInputBorder(),
                  prefixIcon: const Icon(Icons.text_fields),
                  suffixIcon: _isLoadingName
                      ? const SizedBox(
                    width: 20,
                    height: 20,
                    child: CircularProgressIndicator(strokeWidth: 2),
                  )
                      : null,
                ),
                readOnly: true,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请先输入有效的股票代码';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: _priceController,
                decoration: const InputDecoration(
                  labelText: '买入价格*',
                  border: OutlineInputBorder(),
                  prefixIcon: Icon(Icons.attach_money),
                ),
                keyboardType: TextInputType.numberWithOptions(decimal: true),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入买入价格';
                  }
                  final price = double.tryParse(value);
                  if (price == null || price <= 0) {
                    return '请输入有效的价格';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: _quantityController,
                decoration: const InputDecoration(
                  labelText: '买入数量*',
                  border: OutlineInputBorder(),
                  prefixIcon: Icon(Icons.format_list_numbered),
                ),
                keyboardType: TextInputType.number,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入买入数量';
                  }
                  final quantity = int.tryParse(value);
                  if (quantity == null || quantity <= 0) {
                    return '请输入有效的数量';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),
              InkWell(
                onTap: () => _selectDate(context),
                child: InputDecorator(
                  decoration: const InputDecoration(
                    labelText: '买入日期*',
                    border: OutlineInputBorder(),
                    prefixIcon: Icon(Icons.calendar_today),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        '${_selectedDate.year}-${_selectedDate.month.toString().padLeft(2, '0')}-${_selectedDate.day.toString().padLeft(2, '0')}',
                      ),
                      const Icon(Icons.calendar_today),
                    ],
                  ),
                ),
              ),
              const SizedBox(height: 24),
              SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  onPressed: _submitForm,
                  style: ElevatedButton.styleFrom(
                    padding: const EdgeInsets.symmetric(vertical: 16),
                  ),
                  child: const Text('更新买入记录'),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}